package com.alinesno.cloud.monitor.agent.tool;

import java.net.InetAddress;
import java.net.UnknownHostException;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 获取到IP地址
 * 
 * @author WeiXiaoJin
 * @since 2019年4月8日 下午8:54:26
 */
public class IPUtils {

	public static final String IP;
	public static final String HOSTNAME;
	private static final Logger log = LoggerFactory.getLogger(IPUtils.class);

	static {
		String ip;
		String hostname;
		try {
			InetAddress addr = InetAddress.getLocalHost();
			ip = addr.getHostAddress();
			hostname = addr.getHostName();
		} catch (UnknownHostException e) {
			log.error("Can't find out address: " + e.getMessage());
			ip = "UNKNOWN";
			hostname = "UNKNOWN";
		}
		if (ip.equals("127.0.0.1") || ip.equals("::1") || ip.equals("UNKNOWN")) {
			try {
				Process process = Runtime.getRuntime().exec("hostname -i");
				if (process.waitFor() == 0) {
					ip = new String(IOUtils.toByteArray(process.getInputStream()), "UTF8");
				}
				process = Runtime.getRuntime().exec("hostname");
				if (process.waitFor() == 0) {
					hostname = (new String(IOUtils.toByteArray(process.getInputStream()), "UTF8")).trim();
				}
			} catch (Exception e) {
				log.warn("get hostname failed {}", e.getMessage());
			}
		}
		IP = ip;
		HOSTNAME = hostname;
		log.info("IP {} HOSTNAME {}", IP, HOSTNAME);
	}

	/**
	 * 获取IP地址
	 * 
	 * 使用Nginx等反向代理软件， 则不能通过request.getRemoteAddr()获取IP地址
	 * 如果使用了多级反向代理的话，X-Forwarded-For的值并不止一个，而是一串IP地址，X-Forwarded-For中第一个非unknown的有效IP字符串，则为真实IP地址
	 */
	public static String getIpAddr(HttpServletRequest request) {

		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
	}

}